import 'dart:io';

import 'package:dsp48_v10/src/modules/eq/my_eq.dart';
import 'package:dsp48_v10/src/modules/home/my_home.dart';
import 'package:dsp48_v10/src/modules/in/my_in.dart';
import 'package:dsp48_v10/src/modules/out/my_out.dart';
import 'package:dsp48_v10/src/modules/time/my_time.dart';
import 'package:dsp48_v10/src/tool/assets.dart';
import 'package:flutter_kit_dsp/flutter_kit_dsp.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import 'src/modules/xo/my_xo.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future<void> main() async {
  /// 捕获所有未捕获的 Dart 异常
  LogManager.initFireBase(
      crashTest: false,
      runMain: () async {
        requestPermission();
        initRealm();
        registerDelegate();
        BluetoothManager.key = navigatorKey;

        // SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight])
        SystemChrome.setPreferredOrientations(
            [Platform.isAndroid ? DeviceOrientation.landscapeLeft : DeviceOrientation.landscapeRight]).then((_) {
          GetxManager.initGetx();
          runApp(const MyApp());
        });
      });
}

void registerDelegate() {
  CHDefaultConfig().inNumbers = 4;
  CHDefaultConfig().imgs = [
    assets.soud_f_l_off,
    assets.soud_f_r_off,
    assets.soud_m_l_off,
    assets.soud_m_r_off,
    assets.soud_m_l_off,
    assets.soud_m_r_off,
    assets.soud_b_off,
    assets.soud_b_off
  ];
  CHDefaultConfig().highLightImgs = [
    assets.soud_f_l_on,
    assets.soud_f_r_on,
    assets.soud_m_l_on,
    assets.soud_m_r_on,
    assets.soud_m_l_on,
    assets.soud_m_r_on,
    assets.soud_b_on,
    assets.soud_b_on
  ];

  CHDefaultConfig().signList = [25, 40, 63, 100, 160, 250, 400, 630, 1000, 1600, 2500, 4000, 6300, 10000, 16000];
  CHDefaultConfig().sign_sample.Q = 1.4;
  CHDefaultConfig().sign_sample.max_Q = 10;
  CHDefaultConfig().sign_sample.min_gain = -12;
  CHDefaultConfig().sign_sample.max_gain = 12;
  DelegateRegistry.register<HomePageDelegate>(() => MyHome());
  DelegateRegistry.register<EqPageDelegate>(() => MyEqq());
  DelegateRegistry.register<SumPageDelegate>(() => MyIn());
  DelegateRegistry.register<GainPageDelegate>(() => MyOut());
  DelegateRegistry.register<DelayPageDelegate>(() => MyTime());
  DelegateRegistry.register<CrossoverPageDelegate>(() => MyXo());
}

void initRealm() {
  // // 创建不同模型的 RealmManager 实例
  RealmManager.schemaVersion = 11;
  RealmManager<GlobalModel>(
    allSchemas: [
      SignModel.schema,
      PassType.schema,
      Passmodel.schema,
      ChannelModel.schema,
      VolumeModel.schema,
      REMModel.schema,
      GlobalModel.schema
    ],
  );
  // 创建不同模型的 RealmManager 实例
}

Future<void> requestPermission() async {
  BluetoothManager.instance.requestPermissions();
  await Permission.microphone.request();
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // 隐藏状态栏
    /// SystemUiMode.immersiveSticky：隐藏状态栏和导航栏，用户可以从屏幕边缘滑动重新显示。
    /// SystemUiMode.immersive：隐藏状态栏和导航栏，但不会自动重新显示。
    /// SystemUiMode.leanBack：隐藏状态栏和导航栏，但更容易重新显示。
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.black, // 状态栏背景色
      statusBarIconBrightness: Brightness.light, // 状态栏图标颜色 (白色图标)
    ));

    return GetMaterialApp(
      navigatorKey: navigatorKey,
      locale: const Locale('zh'),
      localizationsDelegates: Flutter_Kit_Share_Localizations.localizationsDelegates,
      supportedLocales: Flutter_Kit_Share_Localizations.supportedLocales,
      title: 'MASSIVE',
      debugShowCheckedModeBanner: false,
      initialRoute: AppPages.INITIAL,
      getPages: AppPages.routes,
      theme: ThemeData(
        // 设置全局 AppBar 主题
        appBarTheme: const AppBarTheme(
          centerTitle: true,
          backgroundColor: Colors.transparent, // AppBar 背景颜色
          elevation: 0,
          titleTextStyle: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), // AppBar 标题文本颜色
        ),

        // 设置全局文本颜色
        textTheme: const TextTheme(
          bodySmall: TextStyle(color: Colors.white), // 小号文本颜色
          bodyMedium: TextStyle(color: Colors.white), // 中号文本颜色
          bodyLarge: TextStyle(color: Colors.white), // 大号文本颜色
        ),

        ///全局slider设置
        sliderTheme: SliderThemeData(
          trackHeight: 7,
          activeTrackColor: Color_theme, // 滑动过的颜色
          inactiveTrackColor: Colors.white, // 未滑动部分的颜色
          // activeTrackColor: Colors.transparent, // 滑动过的颜色
          // inactiveTrackColor: Colors.transparent, // 未滑动部分的颜色
          thumbColor: Color_thumbColor, // 滑块的颜色
          overlayColor: Colors.red.withOpacity(0.2), // 滑块按下时的颜色
          activeTickMarkColor: Colors.transparent, // 隐藏刻度线
          inactiveTickMarkColor: Colors.transparent, // 隐藏刻度线
          thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 10.0), // 自定义滑块的形状和大小
          overlayShape: const RoundSliderOverlayShape(overlayRadius: 0.0), // 设置圆点到两端的间距为 0 以减小间距
          trackShape: null,

          // thumbIcon: Image.asset('assets/slider_thumb.png'), // 自定义滑点图片
        ),

        switchTheme: SwitchThemeData(
            // trackColor: WidgetStatePropertyAll(Color(0xFF00A1D5)),
            trackColor: WidgetStateProperty.resolveWith((states) {
              if (states.contains(WidgetState.selected)) {
                return Color_theme; // 打开状态的背景颜色
              }
              return Color_disEnable; // 关闭状态的背景颜色
            }),
            trackOutlineColor: const WidgetStatePropertyAll(Colors.black),
            trackOutlineWidth: const WidgetStatePropertyAll(1),
            overlayColor: const WidgetStatePropertyAll(Colors.transparent),
            thumbColor: const WidgetStatePropertyAll(Color_thumbColor)),

        highlightColor: Colors.red, // 按钮等组件点击时的高亮颜色
        splashColor: Colors.blue, // 点击时的水波纹颜色
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),

        useMaterial3: true,
      ),
      builder: (context, child) {
        return MediaQuery(
          //限制字体不会因系统字体放大而影响
          data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
          child: EasyLoading.init()(context, child),
        );
      },
    );
  }
}
